<?php
namespace App\Jobs;

use DB;
use App\Jobs\Job;

use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldQueue;

require __DIR__.'/../Library/wechat/autoload.php';

use Overtrue\Wechat\Auth;
use Overtrue\Wechat\Notice;

class SendWechat extends Job implements SelfHandling, ShouldQueue
{
	protected $id;
	protected $openId;
	protected $templateId;
    protected $url;
    protected $color;
    protected $data;
    /**
     * Create a new job instance.
     *
     * @param  User  $user
     * @return void
     */
    public function __construct($data)
    {
    	$this->id 			= $data["id"];
    	$this->openId 		= $data["openid"];
    	$this->templateId   = $data["tpl_id"];
        $this->url          = $data["url"];
        $this->color        = $data["color"];
        $this->data         = $data["data"];
    }

    /**
     * Execute the job.
     *
     * @param  Mailer  $mailer
     * @return void
     */
    public function handle()
    {
        $appId  = env("WECHAT_APP_ID");
        $secret = env("WECHAT_SECRET");

        $notice = new Notice($appId, $secret);
        
        //发送
        $sendTime = date("Y-m-d H:i:s");
        try{
            $messageId = $notice->send($this->openId, $this->templateId,$this->data, $this->url, $this->color);
            $result    = ["send_code"=>"1","send_time"=>$sendTime,"send_detail"=>$messageId];
        }catch(Exception $e){
            $result    = ["send_code"=>"-1","send_time"=>$sendTime,"send_detail"=>json_encode($e)];
        }

        DB::table("im_inform_user_method")->where("id",$this->id)->update($result);
        return true; 
    }
}